#include "StdAfx.h"
#include "DropDownWnd.h"
#include "DropDownUI.h"
#include "ControlCanvasUI.h"
#include "VerticalLayoutUI.h"
#include "ControlUI.h"

CDropDownWnd::CDropDownWnd(void)
{
}

CDropDownWnd::~CDropDownWnd(void)
{
}

void CDropDownWnd::Init(CDropDownUI* pOwner)
{
	m_pOwner = pOwner;
	m_iOldSel = m_pOwner->GetCurSel();
	// Position the popup window in absolute space
	SIZE szDrop = m_pOwner->GetDropDownSize();
	RECT rc = pOwner->GetPos();
	rc.top = rc.bottom;
	rc.bottom = rc.top + szDrop.cy;
	if( szDrop.cx > 0 ) rc.right = rc.left + szDrop.cx;
	MapWindowRect(pOwner->GetManager()->GetPaintWindow(), HWND_DESKTOP, &rc);
	Create(pOwner->GetManager()->GetPaintWindow(), NULL, WS_POPUP | WS_BORDER, WS_EX_TOOLWINDOW, rc,(HMENU)NULL);
	// HACK: Don't deselect the parent's caption
	HWND hWndParent = m_hWnd;
	while( ::GetParent(hWndParent) != NULL ) hWndParent = ::GetParent(hWndParent);
	::ShowWindow(m_hWnd, SW_SHOW);
	::SendMessage(hWndParent, WM_NCACTIVATE, TRUE, 0L);
}

LPCTSTR CDropDownWnd::GetWindowClassName() const
{
	return _T("DropDownWnd");
}

void CDropDownWnd::OnFinalMessage(HWND hWnd)
{
	delete this;
}

LRESULT CDropDownWnd::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	if( uMsg == WM_CREATE ) {     
		m_pm.Init(m_hWnd);
		// The trick is to add the items to the new container. Their owner gets
		// reassigned by this operation - which is why it is important to reassign
		// the items back to the righfull owner/manager when the window closes.
		CControlCanvasUI* pWindow = new CControlCanvasUI;
		CVerticalLayoutUI* pLayout = new CVerticalLayoutUI;
		for( int i = 0; i < m_pOwner->GetCount(); i++ ) pLayout->Add(static_cast<CControlUI*>(m_pOwner->GetItem(i)));
		pLayout->SetAutoDestroy(false);
		pLayout->EnableScrollBar(true);
		pWindow->Add(pLayout);
		m_pm.AttachDialog(pWindow);
		return 0;
	}
	else if( uMsg == WM_CLOSE ) {
		m_pOwner->SetManager(m_pOwner->GetManager(), m_pOwner->GetParent());
		m_pOwner->SetPos(m_pOwner->GetPos());
		m_pOwner->SetFocus();
	}
	else if( uMsg == WM_LBUTTONUP ) {
		PostMessage(WM_KILLFOCUS);
	}
	else if( uMsg == WM_KEYDOWN ) {
		switch( wParam ) {
	  case VK_ESCAPE:
		  m_pOwner->SelectItem(m_iOldSel);
		  // FALL THROUGH...
	  case VK_RETURN:
		  PostMessage(WM_KILLFOCUS);
		  break;
	  default:
		  TEventUI event;
		  event.Type = UIEVENT_KEYDOWN;
		  event.chKey = wParam;
		  m_pOwner->Event(event);
		  return 0;
		}
	}
	else if( uMsg == WM_KILLFOCUS ) {
		if( m_hWnd != (HWND) wParam ) PostMessage(WM_CLOSE);
	}
	LRESULT lRes = 0;
	if( m_pm.MessageHandler(uMsg, wParam, lParam, lRes) ) return lRes;
	return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
}